<template>
  <transition name="message-fade" @after-leave="handleAfterLeave">
    <div
      :class="['cg-message', props.type ? `cg-message--${props.type}` : '']"
      :style="positionStyle"
      v-show="visible"
      @mouseenter="clearTimer"
      @mouseleave="startTimer"
    >
      <p class="cg-message__content">
        {{ props.message }}
      </p>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue';

// 定义组件props和默认值
const props = withDefaults(defineProps<{
  message: string;
  duration?: number;
  type?: 'info' | 'success' | 'warning' | 'error';
  onClose?: (instance: any) => void;
}>(), {
  duration: 3000,
  type: 'info'
});

// 响应式数据
const visible = ref(false);
const closed = ref(false);
const positionStyle = ref<Record<string, string>>({});
let timer: ReturnType<typeof setTimeout> | null = null;

// 监听
watch(
  closed,
  (newVal) => {
    if (newVal) {
      visible.value = false;
    }
  }
);

// 生命周期
onMounted(() => {
  visible.value = true;
  startTimer();
});

onUnmounted(() => {
  // 清理计时器
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
});

// 方法
const handleAfterLeave = () => {
  // 在组合式API中，不需要手动销毁组件
  // Vue会自动处理组件的卸载
};

const close = () => {
  closed.value = true;
  if (typeof props.onClose === 'function') {
    props.onClose({ visible, message: props.message, duration: props.duration, type: props.type, close });
  }
};

const clearTimer = () => {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
};

const startTimer = () => {
  if (props.duration > 0) {
    clearTimer(); // 先清理已有计时器
    timer = setTimeout(() => {
      if (!closed.value) {
        close();
      }
    }, props.duration);
  }
};

// 暴露方法给父组件
defineExpose({
  close
});
</script>

<style lang="scss">
@use './style.scss';
</style>
